#include "Geom.h"

Geom::Geom()
{
	m_device = 0;
	m_geomEffect = 0;
	m_vertexBuffer = 0;
	m_vertexDeclaration = 0;
}

Geom::Geom( D3DDevice device, GeomEffect & effect )
{
	m_vertexBuffer = 0;
	initialize( device, effect );
}

Geom::~Geom(void)
{
	destroy();
}

void Geom::initialize( D3DDevice device, GeomEffect & geomEffect )
{
	m_device = device;
	m_geomEffect = &geomEffect;

	D3DVERTEXELEMENT9 declaration[] = {
		{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
		D3DDECL_END()
	};

	m_device->CreateVertexDeclaration( declaration, &m_vertexDeclaration );
}

void Geom::destroy()
{
	SAFE_RELEASE( m_vertexBuffer );
	SAFE_RELEASE( m_vertexDeclaration );
}

void Geom::render()
{
	if( m_vertexBuffer == 0 )
		return;

	m_device->SetStreamSource( 0, m_vertexBuffer, 0, sizeof(float3) );
	m_device->SetVertexDeclaration( m_vertexDeclaration );

	uint32 cPasses;
	m_geomEffect->effect()->Begin( &cPasses, 0 );
	for( int pass = 0; pass < cPasses; pass++ )
	{
		m_geomEffect->effect()->BeginPass( pass );
			m_geomEffect->effect()->CommitChanges();

			m_device->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, m_vertices.size()-2 );

		m_geomEffect->effect()->EndPass();
	}
	m_geomEffect->effect()->End();
}

void Geom::setVertices( Geom::Vertices const &vertices )
{
	m_vertices = vertices;
	SAFE_RELEASE( m_vertexBuffer );

	uint32 byteLength = sizeof(float3)*vertices.size();
	if( byteLength == 0 )
		return;

	m_device->CreateVertexBuffer(
		byteLength,
		0, // usage
		0, // not FVF
		D3DPOOL_MANAGED,
		&m_vertexBuffer,
		0 );// shared handle

	void * data;
	m_vertexBuffer->Lock( 0, 0, & data, 0 );
	memcpy( data, & m_vertices[0], byteLength );
	m_vertexBuffer->Unlock();
}

Geom::Vertices const & Geom::vertices() const
{
	return m_vertices;
}
